/**
 * @file   colorline.cpp
 * @author wolfhead <wolfhead@wolfhead-laptop>
 * @date   Mon Dec  5 20:11:19 2011
 * 
 * @brief  
 * 
 * 
 */
#include <iostream>
#include <getopt.h>
#include "colorConfig.h"


int GetVersionInfo()
{
    std::cout << "colorline version 0.1" << std::endl;
    return 0;
}

int GetHelp()
{
    GetVersionInfo();
    std::cout << "\tusage: linecolor -cvh" << std::endl
              << "\t - To make all lines contain ERROR become red:" << std::endl
              << "\t - ?> linecolor -c \"contain ERROR red\"" << std::endl
              << std::endl
              << "\t - To make all lines contain ERROR become red and INFO green:" << std::endl
              << "\t - ?> linecolor -c \"contain ERROR red | contain INFO green\"" << std::endl
              << std::endl
              
              << "\t Options:" << std::endl
              << "\t-c color-config [rule|rule|rule|...]" << std::endl
              << "\t\t contain [string] [color]" << std::endl
              << "\t\t match   [regex]  [color]" << std::endl
              << "\t\t color could be one of [white|black|red|blue|yellow|green" << std::endl

              << "\t-v versionInfo" << std::endl
              << "\t-h help" << std::endl;
    return 0;
}


int main(int argc, char * argv[])
{

    const char * optionFormat = "c:vh";
    option longOption[] =
		{
		    {"color-config", 0, 0, 'c'},
		    {"version", 0, 0, 'v'},
            {"help", 0, 0, 'h'},
		    {NULL, 0, 0, 0}
		};		

    std::string colorConfig =
        "contain error red|" 
        "contain ERROR red|" 
        "contain info green|"
        "contain INFO green|"
        "contain warning yellow|"
        "contain WARNING yellow|";

    while(true)
    {
        int optionIndex = 0;
        int c = getopt_long(
            argc, 
            argv, 
            optionFormat, 
            longOption, 
            &optionIndex);

        if (c == -1) break;

        switch(c)
        {
        case 0: // long option, not need process
            break;
        case 'c':
            colorConfig = optarg; 
            break;
        case 'v':
            GetVersionInfo();
            return 0;
        case 'h':
            GetHelp();
            return 0;
        default:
            printf("Invalid option: -%c %s\n", c, optarg);
            GetHelp();
            return -1;
        }
    }

    ColorConfig config;

    if (0 != config.LoadConfig(colorConfig))
    {
        return -1;
    }

    char * buffer = new char[40960];

    while (std::cin.getline(buffer, 40960))
    {
        std::string line(buffer);

        std::cout 
            << config.ParseLine(line)  
            << line 
            << config.GetDefaultColor()
            << std::endl;
    }

    delete [] buffer;

    return 0;
}
